package com.example.electricbicycle.controller;

import com.example.electricbicycle.po.SalesAdmin;
import com.example.electricbicycle.service.SalesAdminService;
import com.example.electricbicycle.service.SalesAdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@WebServlet("/salesAdmin")
public class SalesAdminServlet extends HttpServlet {
    private final SalesAdminService saleService = new SalesAdminServiceImpl();
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        if ("list".equals(action) || action == null) {

            String id = request.getParameter("id");
            if(id != null) {
                SalesAdmin sale = saleService.getSaleById(Integer.parseInt(id));

                List<SalesAdmin> list = Arrays.asList(sale);
                request.setAttribute("sales", list);

            }else{
                List<SalesAdmin> sales = saleService.getAllSales();
                request.setAttribute("sales", sales);

            }


            request.getRequestDispatcher("/salesadmin/saleslist.jsp").forward(request, response);

        }
        else if ("addForm".equals(action)) {
            request.getRequestDispatcher("/salesadmin/addsale.jsp").forward(request, response);

        } else if ("editForm".equals(action)) {
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                SalesAdmin sale = saleService.getSaleById(id);

                if (sale != null) {
                    request.setAttribute("sale", sale);
                    request.setAttribute("saleTimeStr", sdf.format(sale.getSaleTime()));
                    request.getRequestDispatcher("/salesadmin/editsale.jsp").forward(request, response);
                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "订单不存在");
                }
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "订单ID格式错误");
            }

        } else if ("delete".equals(action)) {
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                if (saleService.deleteSale(id)) {
                    response.sendRedirect(request.getContextPath() + "/salesAdmin?action=list");
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "删除失败");
                }
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "订单ID格式错误");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        if ("add".equals(action)) {
            try {
                SalesAdmin sale = new SalesAdmin();
                sale.setCustomerId(Integer.parseInt(request.getParameter("customerId")));
                sale.setUserId(Integer.parseInt(request.getParameter("userId")));
                sale.setVehicleId(Integer.parseInt(request.getParameter("vehicleId")));
                sale.setQuantity(Integer.parseInt(request.getParameter("quantity")));
                sale.setStatus(Integer.parseInt(request.getParameter("status")));
                sale.setSaleTime(sdf.parse(request.getParameter("saleTime")));

                if (saleService.addSale(sale)) {
                    response.sendRedirect(request.getContextPath() + "/salesAdmin?action=list");
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "添加失败");
                }
            } catch (NumberFormatException | ParseException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "参数格式错误: " + e.getMessage());
            }

        } else if ("update".equals(action)) {
            try {

                int id = Integer.parseInt(request.getParameter("id"));
                if (saleService.getSaleById(id) == null) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "订单不存在");
                    return;
                }

                SalesAdmin sale = new SalesAdmin();
                sale.setId(id);
                sale.setCustomerId(Integer.parseInt(request.getParameter("customerId")));
                sale.setUserId(Integer.parseInt(request.getParameter("userId")));
                sale.setVehicleId(Integer.parseInt(request.getParameter("vehicleId")));
                sale.setQuantity(Integer.parseInt(request.getParameter("quantity")));
                sale.setStatus(Integer.parseInt(request.getParameter("status")));
                sale.setSaleTime(sdf.parse(request.getParameter("saleTime")));

                if (saleService.updateSale(sale)) {

                    response.sendRedirect(request.getContextPath() + "/salesAdmin?action=list");
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "更新失败");
                }
            } catch (NumberFormatException | ParseException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "参数格式错误: " + e.getMessage());
            }
        }
    }
}